/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.biz.modular.goods.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import vip.xiaonuo.biz.modular.event.service.BizEventGoodsCheckService;
import vip.xiaonuo.biz.modular.goods.entity.BizGoods;
import vip.xiaonuo.biz.modular.goods.entity.BizGoodsCheck;
import vip.xiaonuo.biz.modular.goods.entity.BizGoodsLedger;
import vip.xiaonuo.biz.modular.goods.entity.BizGoodsLedgerCheck;
import vip.xiaonuo.biz.modular.goods.mapper.BizGoodsCheckMapper;
import vip.xiaonuo.biz.modular.goods.mapper.BizGoodsLedgerCheckMapper;
import vip.xiaonuo.biz.modular.goods.mapper.BizGoodsLedgerMapper;
import vip.xiaonuo.biz.modular.goods.param.ClientCheckGoodsCheckItemsParam;
import vip.xiaonuo.biz.modular.goods.service.BizGoodsLedgerCheckService;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 物品借用检查Service接口实现类
 *
 * @author 古月墨塵
 * @date 2022/12/03 23:50
 **/
@Service
@Transactional
public class BizGoodsLedgerCheckServiceImpl extends ServiceImpl<BizGoodsLedgerCheckMapper, BizGoodsLedgerCheck> implements BizGoodsLedgerCheckService {
    @Resource
    private BizGoodsLedgerMapper bizGoodsLedgerMapper;
    @Resource
    private BizGoodsCheckMapper bizGoodsCheckMapper;

    @Resource
    private BizEventGoodsCheckService bizEventGoodsCheckService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void checkGoodsCheckItemForClient(ClientCheckGoodsCheckItemsParam param) {
        BizGoodsLedger bizGoodsLedger = bizGoodsLedgerMapper.selectById(param.getLedgerId());
        Assert.notNull(bizGoodsLedger, "借用记录不存在");

        if (bizGoodsLedger.getReturnFlag() == 1) {
            throw new IllegalArgumentException("物品已归还，无法再次操作");
        }
        // 如果是借用检查项，并且借用检查项已经确认
        if (param.getCheckType() == 0 && bizGoodsLedger.getUserBorrowCheckConfirmed()) {
            throw new IllegalArgumentException("借用检查已确认，无法再次修改");
        }
        if (param.getCheckType() == 1 && bizGoodsLedger.getUserReturnCheckConfirmed()) {
            throw new IllegalArgumentException("归还检查已确认，无法再次修改");
        }

        param.getCheckItems().forEach(checkItem -> {
            BizGoodsCheck bizGoodsCheck = bizGoodsCheckMapper.selectById(checkItem.getCheckId());
            if (bizGoodsCheck == null) return; // 如果检查项不存在，直接跳过。
            BizGoodsLedgerCheck bizGoodsLedgerCheck = new BizGoodsLedgerCheck();
            bizGoodsLedgerCheck.setLedgerId(bizGoodsLedger.getId());
            bizGoodsLedgerCheck.setGoodsId(bizGoodsLedger.getGoodsId());
            bizGoodsLedgerCheck.setCheckType(param.getCheckType());
            bizGoodsLedgerCheck.setCheckDes(bizGoodsCheck.getCheckDes());
            bizGoodsLedgerCheck.setCheckId(checkItem.getCheckId());
            bizGoodsLedgerCheck.setCheckItem(bizGoodsCheck.getCheckItem());
            bizGoodsLedgerCheck.setCheckResult(checkItem.getCheckResult());
            bizGoodsLedgerCheck.setCheckRemark(checkItem.getCheckRemark());
            bizGoodsLedgerCheck.setCheckFiles(String.join(",", checkItem.getImages()));

            BizGoodsLedgerCheck existOne = getOne(new LambdaQueryWrapper<BizGoodsLedgerCheck>()
                    .eq(BizGoodsLedgerCheck::getDeleteFlag, "NOT_DELETE")
                    .eq(BizGoodsLedgerCheck::getLedgerId, param.getLedgerId())
                    .eq(BizGoodsLedgerCheck::getCheckId, checkItem.getCheckId())
                    .last("limit 1"));

            if (existOne != null) bizGoodsLedgerCheck.setId(existOne.getId());
            saveOrUpdate(bizGoodsLedgerCheck);
        });

        if (param.getCheckConfirmed()) { // 如果已被确认
            BizGoodsLedger bgl = new BizGoodsLedger();
            bgl.setId(param.getLedgerId());
            if (param.getCheckType() == 0) bgl.setUserBorrowCheckConfirmed(true); // 如果是借用
            if (param.getCheckType() == 1) bgl.setUserReturnCheckConfirmed(true); // 如果是归还
            bizGoodsLedgerMapper.updateById(bgl); // 更新租表的借还是否检查确认的两个字段
            //触发 检查事件
            bizEventGoodsCheckService.handleCheckForNorm(param.getLedgerId(), param.getCheckType());
        }
    }

    @Override
    public void addGoodsLedgerChecks(BizGoods goods, BizGoodsLedger goodsLedger) {
        //借用检查项
        List<BizGoodsLedgerCheck> borChecks = new ArrayList<>();
        //归还检查项
        List<BizGoodsLedgerCheck> retChecks = new ArrayList<>();
        //物品检查项
        List<BizGoodsCheck> goodsCheckList = bizGoodsCheckMapper.getListByGoodsId(goods.getId());
        for (BizGoodsCheck goodsCheck : goodsCheckList) {
            BizGoodsLedgerCheck ledgerCheck = new BizGoodsLedgerCheck();
            ledgerCheck.setLedgerId(goodsLedger.getId());
            ledgerCheck.setGoodsId(goods.getId());
            ledgerCheck.setCheckId(goodsCheck.getId());
            ledgerCheck.setCheckItem(goodsCheck.getCheckItem());
            ledgerCheck.setCheckDes(goodsCheck.getCheckDes());
            if (goodsCheck.getBorrowCheck() == 1) {
                BizGoodsLedgerCheck temp = new BizGoodsLedgerCheck();
                BeanUtil.copyProperties(ledgerCheck, temp);
                temp.setCheckType(0);
                //借用
                borChecks.add(temp);
            }
            if (goodsCheck.getReturnInsp() == 1) {
                BizGoodsLedgerCheck temp = new BizGoodsLedgerCheck();
                BeanUtil.copyProperties(ledgerCheck, temp);
                temp.setCheckType(1);
                //归还
                retChecks.add(temp);
            }
        }
        if (!CollectionUtils.isEmpty(borChecks)) {
            this.saveBatch(borChecks);
        }
        if (!CollectionUtils.isEmpty(retChecks)) {
            this.saveBatch(retChecks);
        }
    }

    @Override
    public List<BizGoodsLedgerCheck> getListByLedgerIdAndCheckType(String ledgerId, Integer checkType) {
        return this.baseMapper.getListByLedgerIdAndCheckType(ledgerId, checkType);
    }
}
